package controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import restaurant.MenuCategory;
import restaurant.MenuItem;
import restaurant.Tag;

/**
 * Servlet implementation class MenuEdit
 */
@WebServlet("/Edit%20Menu")
public class MenuEdit extends Menu {
    private static final long serialVersionUID = 201211021341L;

    @Override
    protected Map<String, String> getLinkMap() {
        return LinkData.getAdminLinkMap();
    }

    @Override
    protected String getDispatcherPage() {
        return "/WEB-INF/menu_edit.jsp";
    }

    @Override
    protected void doPost(final HttpServletRequest req, final HttpServletResponse resp)
            throws ServletException, IOException {
        final String id = req.getParameter("id");
        final String name = req.getParameter("name");
        final String number = req.getParameter("number");
        final String description = req.getParameter("description");
        final String price = req.getParameter("price");
        final String categoryName = req.getParameter("category");
        final String tagArray[] = req.getParameterValues("tags");

        final EntityManager em = _emf.createEntityManager();

        final List<Tag> tagList = new ArrayList<Tag>();
        List<Tag> tags = em.createQuery("select t from Tag t", Tag.class).getResultList();
        if (null != tagArray) {
            for (int i = 0; i < tagArray.length; i++) {
                for (final Tag t : tags) {
                    if (t.getName().equals(tagArray[i])) {
                        tagList.add(t);
                        break;
                    }
                }
            }
        }

        List<MenuCategory> categories = em.createQuery("select c from MenuCategory c", MenuCategory.class).getResultList();
        MenuCategory menuCategory = categories.get(0);
        for (MenuCategory c : categories) {
            if (c.getName().equalsIgnoreCase(categoryName)) {
                menuCategory = c;
                break;
            }
        }

        em.getTransaction().begin();
        MenuItem oldMenuItem = null;
        if(null != id && !(id.isEmpty())) {
            oldMenuItem = em.find(MenuItem.class, Integer.parseInt(id));
        }
        if (null == oldMenuItem) {
            MenuItem newMenuItem = new MenuItem();
            newMenuItem.setName(name);
            newMenuItem.setNumber(Integer.parseInt(number));
            newMenuItem.setDescription(description);
            newMenuItem.setPrice(Float.parseFloat(price));
            newMenuItem.setCategory(menuCategory);
            newMenuItem.setTags(tagList);
            em.persist(newMenuItem);
        } else {
            oldMenuItem.setName(name);
            oldMenuItem.setNumber(Integer.parseInt(number));
            oldMenuItem.setDescription(description);
            oldMenuItem.setPrice(Float.parseFloat(price));
            oldMenuItem.setCategory(menuCategory);
            oldMenuItem.setTags(tagList);
            em.merge(oldMenuItem);
        }
        em.getTransaction().commit();

        for (final MenuCategory category : categories) {
            final List<MenuItem> menuItems = new ArrayList<>();
            TypedQuery<MenuItem> q = em.createQuery("select m from MenuItem m where m.category = :category", MenuItem.class);
            q.setParameter("category", category);
            menuItems.addAll(q.getResultList());
            Collections.sort(menuItems, new MenuSorter());

            menuItemsByCategory.put(category.getName(), menuItems);
        }

        req.setAttribute("id", id);
        req.setAttribute("menuItemsByCategory", menuItemsByCategory);

        req.setAttribute("tagIcons", tagIcons);

        req.setAttribute("namesToPages", getLinkMap());
        req.getRequestDispatcher(getDispatcherPage()).forward(req, resp);

        em.close();
    }
}
